<?php
class Library_Model_ChiTietTheMapper extends Library_Model_DataMapperAbstract{
	private static $_instance = null;
	private $_paginator = null;
	
		public function searchByMathe($id)
		{
			$db = $this->getDb();
			$selectCtthe = $db->select()
							->from('tbl_chitietthe')
							->where('MaThe = ?',$id);
			$ctthes = $db->fetchAll($selectCtthe);
		
			$chtheArray = array();
			foreach($ctthes as $chthe)
			{
				
				$thechinhMapper = Library_Model_TheChinhMapper::getInstance();
				$thechinh = $thechinhMapper->searchById($chthe['MaThe']);
				$chthe['tbl_thechinh'] = $thechinh;
				
				$khachhangMapper = Library_Model_KhachHangMapper::getInstance();
				$khachhang = $khachhangMapper->searchByMakhachhang($chthe['MaKhachHang']);
				$chthe['tbl_khachhang'] = $khachhang;
					
				$chtheArray[] = $this->_populate($chthe);
			}
			return $chtheArray;
		}
		public function searchByKhachHang($id)
		{
			$db = $this->getDb();
			$chtheSelect = $db->select()
					   ->from('tbl_chitietthe')
					   ->join('tbl_khachhang','tbl_khachhang.MaKhachHang = tbl_chitietthe.MaKhachHang')
					   ->where('tbl_chitietthe.MaKhachHang = ?',$id);
			$ctthes = $db->fetchAll($chtheSelect);
			$chtheArray = array();
			foreach($ctthes as $chthe)
			{
				$thechinhMapper = Library_Model_TheChinhMapper::getInstance();
				$thechinh = $thechinhMapper->searchById($chthe['MaThe']);
				$chthe['tbl_thechinh'] = $thechinh;
				
				$chtheArray[] =  $this->_populate($chthe);
				
			}
			return $chtheArray;
		}
		protected function _insert(Library_Model_DomainObjectAbstract $obj) {
			$db = $this->getDb();
			/* $madangky = $db->lastInsertId('tbl_dangkykhachhang','MaDangKy'); */
			$data = array(
					'MaKhachHang' => $obj->getMakhachhang(),
					'MaThe' => $obj->getMathechinh(),
			);
			$db->insert('tbl_chitietthe',$data);
				
		}
		
		protected function _update(Library_Model_DomainObjectAbstract $obj) {
		$db = $this->getDb();
		$data = array(
				'MaKhachHang' => $obj->getMakhachhang(),
				'MaThe' => $obj->getMathechinh(),
		);
		$where = $db->quoteInto('ID = ?',$obj->getId());
		$db->update('tbl_chitietthe',$data,$where);
		}

		protected function _populate($data) {
		
		$obj = new Library_Model_ChiTietThe();
		
		$obj->setId($data['MaChiTiet']);
		$obj->setMakhachhang($data['MaThe']);
		$obj->setMathechinh($data['MaKhachHang']);
		$obj->setHocvien($data['tbl_thechinh']);
		$obj->setKhoahoc($data['tbl_khachhang']);
				
		return $obj;
		}
		
		public function delete($id)
		{
			$db = $this->getDb();
			$where = $db->quoteInto('ID = ?',$id);
			$db->delete('tbl_chitietthe',$where);
		}
		
		public static function getInstance()
		{
			if(null === self::$_instance)
			{
				self::$_instance = new self();
			}
			return self::$_instance;
		}
}